<!doctype html>



  


<html class="theme-next mist use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css"/>




  <link href="//fonts.useso.com/css?family=Lato:300,400,700,400italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">



<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=0.5.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="network,　异步, Volley, android," />





  <link rel="alternate" href="/atom.xml" title="Lippi-浮生志" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=0.5.0" />






<meta name="description" content="说到Android的网络库，比较常用的就是Volley和okHttp了，最近重温了下Volley的源码，感觉应该写点什么．Volley 是 Google 推出的 Android 异步网络请求框架和图片加载框架，适合数据量小通信比较频繁的情形．">
<meta property="og:type" content="article">
<meta property="og:title" content="Volley源码分析">
<meta property="og:url" content="http://www.ezlippi.com/blog/2015/08/volley-source-code.html">
<meta property="og:site_name" content="Lippi-浮生志">
<meta property="og:description" content="说到Android的网络库，比较常用的就是Volley和okHttp了，最近重温了下Volley的源码，感觉应该写点什么．Volley 是 Google 推出的 Android 异步网络请求框架和图片加载框架，适合数据量小通信比较频繁的情形．">
<meta property="og:image" content="http://www.ezlippi.com/images/volley.png">
<meta property="og:updated_time" content="2016-02-29T13:54:57.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Volley源码分析">
<meta name="twitter:description" content="说到Android的网络库，比较常用的就是Volley和okHttp了，最近重温了下Volley的源码，感觉应该写点什么．Volley 是 Google 推出的 Android 异步网络请求框架和图片加载框架，适合数据量小通信比较频繁的情形．">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>

  <title> Volley源码分析 | Lippi-浮生志 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  



  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?340874ba9357cbe81570aa4ac1185941";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>






  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner">
<script>
(function(){
    var bp = document.createElement('script');
    bp.src = '//push.zhanzhang.baidu.com/push.js';
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>
            
<div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">Lippi-浮生志</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu menu-left">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-home fa-fw"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-th fa-fw"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-archive fa-fw"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-tags fa-fw"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-user fa-fw"></i> <br />
            
            关于
          </a>
        </li>
      

      
      
      
    </ul>
  

  
    <div class="site-search">
      
  <form class="site-search-form">
  <input type="text" id="st-search-input" class="st-search-input st-default-search-input" />
</form>

<script type="text/javascript">
  (function(w,d,t,u,n,s,e){w['SwiftypeObject']=n;w[n]=w[n]||function(){
    (w[n].q=w[n].q||[]).push(arguments);};s=d.createElement(t);
    e=d.getElementsByTagName(t)[0];s.async=1;s.src=u;e.parentNode.insertBefore(s,e);
  })(window,document,'script','//s.swiftypecdn.com/install/v2/st.js','_st');

  _st('install', 'fLM9qfxyerC6njvM7usy','2.0.0');
</script>



    </div>
  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Volley源码分析
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2015-08-27T00:00:00+08:00" content="2015-08-27">
              2015-08-27
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
                  ， 
                

              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/java/android/" itemprop="url" rel="index">
                    <span itemprop="name">android</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/blog/2015/08/volley-source-code.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="/blog/2015/08/volley-source-code.html" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
	
	<span id="busuanzi_container_page_pv" class="post-meta-item-text">
		&nbsp; | &nbsp;  
	    <span id="busuanzi_value_page_pv"><i class="fa fa-spinner fa-spin"></i></span> Hits
	</span>
        </div>
      </header>
    
	


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>说到Android的网络库，比较常用的就是Volley和okHttp了，最近重温了下Volley的源码，感觉应该写点什么．Volley 是 Google 推出的 Android 异步网络请求框架和图片加载框架，适合数据量小通信比较频繁的情形．<br><a id="more"></a><br>先看一下Volley的设计图：</p>
<p><img src="/images/volley.png" alt=""></p>
<h2 id="请求Request"><a href="#请求Request" class="headerlink" title="请求Request"></a>请求Request</h2><p>Volley里面每一个请求都是继承自Request抽象类，比如图中的StringRequest,JsonRequest,ImageRequest,请求最主要的几个属性有：http请求的方法method,请求资源url,是否应该缓存响应shouldCache,如果缓存的话就会有对应的缓存对象Cache.Entry,以及用来标识请求的序列号mSequence,当然这里的每一个请求是异步的，你还需要注册对应的响应监听器，<code>private final Listener&lt;String&gt; mListener;</code>,这个后面再讲．</p>
<h2 id="请求队列"><a href="#请求队列" class="headerlink" title="请求队列"></a>请求队列</h2><p>请求队列是用来管理所有请求的，里面有四个集合类，如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//这个waitingRequest是因为用户可能重复提交了相同的请求，第一次提交一个请求后</span></span><br><span class="line"><span class="comment">//会在这个Map里添加一个key,表示这个请求已经在处理了，如果再提交相同的请求就会</span></span><br><span class="line"><span class="comment">//把这个请求添加到这个key对应的请求队列里，并把第一次的请求加入到缓存队列里，</span></span><br><span class="line"><span class="comment">//后面再发出这个请求就可以从缓存中获取响应了</span></span><br><span class="line"> <span class="keyword">private</span> <span class="keyword">final</span> Map&lt;String, Queue&lt;Request&lt;?&gt;&gt;&gt; mWaitingRequests =</span><br><span class="line">		<span class="keyword">new</span> HashMap&lt;String, Queue&lt;Request&lt;?&gt;&gt;&gt;();</span><br><span class="line"><span class="comment">//用来存储当前所有的请求</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> Set&lt;Request&lt;?&gt;&gt; mCurrentRequests = <span class="keyword">new</span> HashSet&lt;Request&lt;?&gt;&gt;();</span><br><span class="line"><span class="comment">//这是个优先队列，存储那些需要缓存的请求，处理这类请求时，先从缓存中查询，</span></span><br><span class="line"><span class="comment">//如果缓存miss再把它丢进networkRequest中从网络中获取数据  </span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> PriorityBlockingQueue&lt;Request&lt;?&gt;&gt; mCacheQueue =</span><br><span class="line">		<span class="keyword">new</span> PriorityBlockingQueue&lt;Request&lt;?&gt;&gt;();</span><br><span class="line"><span class="comment">//这个队列用于存储需要直接从网络中获取数据的请求</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> PriorityBlockingQueue&lt;Request&lt;?&gt;&gt; mNetworkQueue =</span><br><span class="line">		<span class="keyword">new</span> PriorityBlockingQueue&lt;Request&lt;?&gt;&gt;();</span><br></pre></td></tr></table></figure>
<p>上面讲到请求是保存在优先队列中，那么请求按照什么排序呢？自然是优先级了，<br>如果优先级一样就按照序列号排序，先进先出．请求一共有四个优先级，如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">enum</span> Priority &#123;</span><br><span class="line">        LOW,</span><br><span class="line">	NORMAL,</span><br><span class="line">	HIGH,</span><br><span class="line">	IMMEDIATE</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>既然是这样那么请求一定实现了java的<code>Comparable</code>接口了，没错，而且正如前面所说请求按照优先级和序列号来排序，如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="annotation">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">compareTo</span><span class="params">(Request&lt;T&gt; other)</span> </span>&#123;</span><br><span class="line">Priority left = <span class="keyword">this</span>.getPriority();</span><br><span class="line">Priority right = other.getPriority();</span><br><span class="line"></span><br><span class="line"><span class="comment">// High-priority requests are "lesser" so they are sorted to the front.</span></span><br><span class="line"><span class="comment">// Equal priorities are sorted by sequence number to provide FIFO ordering.</span></span><br><span class="line"><span class="keyword">return</span> left == right ?</span><br><span class="line">        <span class="keyword">this</span>.mSequence - other.mSequence :</span><br><span class="line">        right.ordinal() - left.ordinal();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="请求分派RequestDispatcher"><a href="#请求分派RequestDispatcher" class="headerlink" title="请求分派RequestDispatcher"></a>请求分派RequestDispatcher</h2><p>Volley里面有两个<code>Dispacher</code>,一个是<code>CacheDispatcher</code>,另一个是<code>NetworkDispatcher</code>,两个都是继承自线程，<code>CacheDispatcher</code>启动后从mCacheQueue里取出请求，根据请求的CacheKey(实际上是url)从缓存中检索数据，如果没有检索到数据就把它重新丢进<code>mNetworkQueue</code>中从网络中获取数据，如果缓存命中同时检查下缓存是否过期，如果缓存过期了照样要重新获取数据，否则调用<code>ResponseDelivery</code>把响应传递给相应的对象(实际上是调用请求注册的相应监听器)．<br>Volley默认启动了４个<code>NetworkDispatcher</code>线程来处理网络请求，为了避免过多的网络请求造成UI卡死，Volley默认把这些线程的优先级设置为后台线程<code>Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);</code></p>
<h2 id="HttpStack"><a href="#HttpStack" class="headerlink" title="HttpStack"></a>HttpStack</h2><p>Volley的<code>NetworkDispatcher</code>线程默认调用的是Network类的<code>HttpStack</code>的方法来执行Http请求，HttpStack的实现有两种，如果系统在 Gingerbread 及之后(即 API Level &gt;= 9)，采用基于 <code>HttpURLConnection</code> 的 HurlStack，如果小于 9，采用基于 HttpClient 的 <code>HttpClientStack</code>。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (stack == <span class="keyword">null</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (Build.VERSION.SDK_INT &gt;= <span class="number">9</span>) &#123;</span><br><span class="line">	stack = <span class="keyword">new</span> HurlStack();</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">	stack = <span class="keyword">new</span> HttpClientStack(AndroidHttpClient.newInstance(userAgent));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>得到了 HttpStack,然后通过它构造一个代表网络（Network）的具体实现BasicNetwork。</p>
<h3 id="HttpURLConnection-和-AndroidHttpClient-HttpClient的封装-如何选择"><a href="#HttpURLConnection-和-AndroidHttpClient-HttpClient的封装-如何选择" class="headerlink" title="HttpURLConnection 和 AndroidHttpClient(HttpClient的封装)如何选择"></a>HttpURLConnection 和 AndroidHttpClient(HttpClient的封装)如何选择</h3><p>在 Froyo(2.2) 之前，HttpURLConnection 有个重大 Bug，调用 close() 函数会影响连接池，导致连接复用失效，所以在 Froyo 之前使用 HttpURLConnection 需要关闭 keepAlive。<br>另外在 Gingerbread(2.3) HttpURLConnection 默认开启了 gzip 压缩，提高了 HTTPS 的性能，Ice Cream Sandwich(4.0) HttpURLConnection 支持了请求结果缓存。<br>再加上 HttpURLConnection 本身 API 相对简单，所以对 Android 来说，在 2.3 之后建议使用 HttpURLConnection，之前建议使用 AndroidHttpClient。</p>
<h3 id="关于-User-Agent"><a href="#关于-User-Agent" class="headerlink" title="关于 User Agent"></a>关于 User Agent</h3><p>通过代码我们发现如果是使用 AndroidHttpClient，Volley 还会将请求头中的 User-Agent 字段设置为 App 的 ${packageName}/${versionCode}，如果异常则使用 “volley/0”，不过这个获取 User-Agent 的操作应该放到 if else 内部更合适。而对于 HttpURLConnection 却没有任何操作，为什么呢？<br>如果用 Fiddler 或 Charles 对数据抓包我们会发现，我们会发现 HttpURLConnection 默认是有 User-Agent 的，类似：</p>
<pre><code>Dalvik/1.6.0 (Linux; U; Android 4.1.1; Google Nexus 4 - 4.1.1 - API 16 - 768x1280_1 Build/JRO03S)
</code></pre><p>经常用 WebView 的同学会也许会发现似曾相识，是的，WebView 默认的 User-Agent 也是这个。实际在请求发出之前，会检测 User-Agent 是否为空，如果不为空，则加上系统默认 User-Agent。在 Android 2.1 之后，我们可以通过</p>
<pre><code>String userAgent = System.getProperty(&quot;http.agent&quot;);
</code></pre><p>得到系统默认的 User-Agent，Volley 如果希望自定义 User-Agent，可在自定义 Request 中重写 getHeaders() 函数</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="annotation">@Override</span></span><br><span class="line"><span class="keyword">public</span> Map&lt;String, String&gt; getHeaders() <span class="keyword">throws</span> AuthFailureError &#123;</span><br><span class="line">    <span class="comment">// self-defined user agent</span></span><br><span class="line">    Map&lt;String, String&gt; headerMap = <span class="keyword">new</span> HashMap&lt;String, String&gt;();</span><br><span class="line">    headerMap.put(<span class="string">"User-Agent"</span>, <span class="string">"android-open-project-analysis/1.0"</span>);</span><br><span class="line">    <span class="keyword">return</span> headerMap;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="DiskBasedCache"><a href="#DiskBasedCache" class="headerlink" title="DiskBasedCache"></a>DiskBasedCache</h2><p>Volley默认是把缓存保存在文件中，并在内存中保存了缓存的头部，缓存头部占的最大内存可以设置，便于快速查询缓存是否存在．CacheHeader的主要属性有<br>文件大小size,缓存的etag,获取缓存的key,ttl,softTtl以及responseHeader.根据key来查询缓存，先从内存中查询是否存在CacheHeader,如果存在再从文件中把响应的data再读出来．每次向缓存中插入数据时先看看是否达到了缓存的最大大小，如果超过了容量就按照LRU算法从缓存中删除一部分数据直到满足需求，LRU算法实现很简单，直接调用LinkedHashMap来实现，<code>private final Map&lt;String, CacheHeader&gt; mEntries = new LinkedHashMap&lt;String, CacheHeader&gt;(16,0.75f,true)</code>.</p>
<h2 id="ByteArrayPool"><a href="#ByteArrayPool" class="headerlink" title="ByteArrayPool"></a>ByteArrayPool</h2><p>ByteArrayPool很有意思，这是一个字节数组池，Volley进行网络操作的时候会把HTTP响应的内容写入到字节数组中，如果频繁的申请大的字节数组可能会对系统性能有所影响，所以Volley采取了对象池的方法来解决频繁申请内存的问题，它的实现也比较简单，用的两个字节数组链表，一个按照使用的先后排序，另一个按照字节数组的大小排序，如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> List&lt;<span class="keyword">byte</span>[]&gt; mBuffersByLastUse = <span class="keyword">new</span> LinkedList&lt;<span class="keyword">byte</span>[]&gt;();</span><br><span class="line"><span class="keyword">private</span> List&lt;<span class="keyword">byte</span>[]&gt; mBuffersBySize = <span class="keyword">new</span> ArrayList&lt;<span class="keyword">byte</span>[]&gt;(<span class="number">64</span>);</span><br></pre></td></tr></table></figure>
<p>池当然也有它的大小限制．申请字节数组的时候从mBuffersBySize中申请一个比请求大小更大的数组给他，如果没找到就调用new从堆中申请一个字节数组返回给它，数组用完之后调用returnBuff返回给数组池中，当数组池的大小超过了规定的大小时，就按照LRU算法删除一些数组．那么这个对象池具体在哪里用上了呢？答案是在BasicNetwork中，调用HttpStack返回了Http响应，然后需要把响应的Entity转换为字节数组，一般我们会用ByteArrayOutputStream来做，但是ByteArrayOutputStream是需要从堆中申请一个字节数组的，所以Volley创建了一个继承自ByteArrayOutputStream的类PoolingByteArrayOutputStream并覆写了相应的方法．不得不佩服谷歌的工程师啊，每个细节都考虑的很周到．</p>
<h2 id="关于Http缓存"><a href="#关于Http缓存" class="headerlink" title="关于Http缓存"></a>关于Http缓存</h2><p>Volley中对Http缓存作了相应的处理，在使用BasicNetwork执行Request之前，会给请求添加相应的缓存首部，利用<code>If-None-Match</code>和<code>If-Modified-Since</code>对过期缓存或者不新鲜缓存，进行请求再验证,代码如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">addCacheHeaders</span><span class="params">(Map&lt;String, String&gt; headers, Cache.Entry entry)</span> </span>&#123;</span><br><span class="line">	<span class="comment">// If there's no cache entry, we're done.</span></span><br><span class="line">	<span class="keyword">if</span> (entry == <span class="keyword">null</span>) &#123;</span><br><span class="line">	    <span class="keyword">return</span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> (entry.etag != <span class="keyword">null</span>) &#123;</span><br><span class="line">	    headers.put(<span class="string">"If-None-Match"</span>, entry.etag);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> (entry.serverDate &gt; <span class="number">0</span>) &#123;</span><br><span class="line">	    Date refTime = <span class="keyword">new</span> Date(entry.serverDate);</span><br><span class="line">	    headers.put(<span class="string">"If-Modified-Since"</span>, DateUtils.formatDate(refTime));</span><br><span class="line">	&#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>同样，在收到Http响应之后，Volley也会检查响应首部中的缓存字段，根据<code>Cache-Control</code>和<code>Expires</code>首部来计算缓存的过期时间。如果两个首部都存在情况下，以<code>Cache-Control</code>为准。代码如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> Cache.<span class="function">Entry <span class="title">parseCacheHeaders</span><span class="params">(NetworkResponse response)</span> </span>&#123;</span><br><span class="line"><span class="keyword">long</span> now = System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">Map&lt;String, String&gt; headers = response.headers;</span><br><span class="line"></span><br><span class="line"><span class="keyword">long</span> serverDate = <span class="number">0</span>;</span><br><span class="line"><span class="keyword">long</span> serverExpires = <span class="number">0</span>;</span><br><span class="line"><span class="keyword">long</span> softExpire = <span class="number">0</span>;</span><br><span class="line"><span class="keyword">long</span> maxAge = <span class="number">0</span>;</span><br><span class="line"><span class="keyword">boolean</span> hasCacheControl = <span class="keyword">false</span>;</span><br><span class="line"></span><br><span class="line">String serverEtag = <span class="keyword">null</span>;</span><br><span class="line">String headerValue;</span><br><span class="line"></span><br><span class="line">headerValue = headers.get(<span class="string">"Date"</span>);</span><br><span class="line"><span class="keyword">if</span> (headerValue != <span class="keyword">null</span>) &#123;</span><br><span class="line">    serverDate = parseDateAsEpoch(headerValue);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">headerValue = headers.get(<span class="string">"Cache-Control"</span>);</span><br><span class="line"><span class="keyword">if</span> (headerValue != <span class="keyword">null</span>) &#123;</span><br><span class="line">    hasCacheControl = <span class="keyword">true</span>;</span><br><span class="line">    String[] tokens = headerValue.split(<span class="string">","</span>);</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; tokens.length; i++) &#123;</span><br><span class="line">        String token = tokens[i].trim();</span><br><span class="line">        <span class="keyword">if</span> (token.equals(<span class="string">"no-cache"</span>) || token.equals(<span class="string">"no-store"</span>)) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (token.startsWith(<span class="string">"max-age="</span>)) &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                maxAge = Long.parseLong(token.substring(<span class="number">8</span>));</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (token.equals(<span class="string">"must-revalidate"</span>) || token.equals(<span class="string">"proxy-revalidate"</span>)) &#123;</span><br><span class="line">            maxAge = <span class="number">0</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">headerValue = headers.get(<span class="string">"Expires"</span>);</span><br><span class="line"><span class="keyword">if</span> (headerValue != <span class="keyword">null</span>) &#123;</span><br><span class="line">    serverExpires = parseDateAsEpoch(headerValue);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">serverEtag = headers.get(<span class="string">"ETag"</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// Cache-Control takes precedence over an Expires header, even if both exist and Expires</span></span><br><span class="line"><span class="comment">// is more restrictive.</span></span><br><span class="line"><span class="keyword">if</span> (hasCacheControl) &#123;</span><br><span class="line">    softExpire = now + maxAge * <span class="number">1000</span>;</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (serverDate &gt; <span class="number">0</span> &amp;&amp; serverExpires &gt;= serverDate) &#123;</span><br><span class="line">    <span class="comment">// Default semantic for Expire header in HTTP specification is softExpire.</span></span><br><span class="line">    softExpire = now + (serverExpires - serverDate);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Cache.Entry entry = <span class="keyword">new</span> Cache.Entry();</span><br><span class="line">entry.data = response.data;</span><br><span class="line">entry.etag = serverEtag;</span><br><span class="line">entry.softTtl = softExpire;</span><br><span class="line">entry.ttl = entry.softTtl;</span><br><span class="line">entry.serverDate = serverDate;</span><br><span class="line">entry.responseHeaders = headers;</span><br><span class="line"></span><br><span class="line"><span class="keyword">return</span> entry;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>读完Volley的源码之后只有一个感觉，就是<code>谷歌出品，必属精品</code>.</p>

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/network-异步-Volley-android/" rel="tag">#network,　异步, Volley, android</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2015/08/linux-zsh.html" rel="next" title="Zsh-Linux下最好的Shell简介">
                <i class="fa fa-chevron-left"></i> Zsh-Linux下最好的Shell简介
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2015/09/android-studio-plugins.html" rel="prev" title="提高效率的Android Studio插件">
                提高效率的Android Studio插件 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <div class="ds-share flat" data-thread-key="/blog/2015/08/volley-source-code.html"
     data-title="Volley源码分析"
     data-content=""
     data-url="http://www.ezlippi.com//blog/2015/08/volley-source-code.html">
  <div class="ds-share-inline">
    <ul  class="ds-share-icons-16">

      <li data-toggle="ds-share-icons-more"><a class="ds-more" href="javascript:void(0);">分享到：</a></li>
      <li><a class="ds-weibo" href="javascript:void(0);" data-service="weibo">微博</a></li>
      <li><a class="ds-qzone" href="javascript:void(0);" data-service="qzone">QQ空间</a></li>
      <li><a class="ds-qqt" href="javascript:void(0);" data-service="qqt">腾讯微博</a></li>
      <li><a class="ds-wechat" href="javascript:void(0);" data-service="wechat">微信</a></li>

    </ul>
    <div class="ds-share-icons-more">
    </div>
  </div>
</div>
      
    </div>
  </div>


          </div>
          

  <p>热评文章</p>
  <div class="ds-top-threads" data-range="weekly" data-num-items="4"></div>


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="/blog/2015/08/volley-source-code.html"
           data-title="Volley源码分析" data-url="http://www.ezlippi.com//blog/2015/08/volley-source-code.html">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.jpg"
               alt="EZLippi" />
          <p class="site-author-name" itemprop="name">EZLippi</p>
          <p class="site-description motion-element" itemprop="description">Easy Lippi</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">63</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>
          
          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">22</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">69</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/EZLippi" target="_blank">
                  
                    <i class="fa fa-github"></i> GitHub
                  
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/ouyanglip" target="_blank">
                  
                    <i class="fa fa-weibo"></i> weibo
                  
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.zhihu.com/people/lippi-ouyang" target="_blank">
                  
                    <i class="fa fa-weibo"></i> zhihu
                  
                </a>
              </span>
            
          
        </div>

        
        

        <div class="links-of-author motion-element">
          
            <p class="site-author-name">友情链接</p>
            
              <span class="links-of-author-item">
                <a href="http://szhshp.org" target="_blank">szhshp的博客</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.zhihu.com/people/lippi-ouyang" target="_blank">友链出租</a>
              </span>
            
          
        </div>

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc-indicator-top post-toc-indicator">
            <i class="fa fa-angle-double-up"></i>
          </div>
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#请求Request"><span class="nav-number">1.</span> <span class="nav-text">请求Request</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#请求队列"><span class="nav-number">2.</span> <span class="nav-text">请求队列</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#请求分派RequestDispatcher"><span class="nav-number">3.</span> <span class="nav-text">请求分派RequestDispatcher</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#HttpStack"><span class="nav-number">4.</span> <span class="nav-text">HttpStack</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#HttpURLConnection-和-AndroidHttpClient-HttpClient的封装-如何选择"><span class="nav-number">4.1.</span> <span class="nav-text">HttpURLConnection 和 AndroidHttpClient(HttpClient的封装)如何选择</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#关于-User-Agent"><span class="nav-number">4.2.</span> <span class="nav-text">关于 User Agent</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#DiskBasedCache"><span class="nav-number">5.</span> <span class="nav-text">DiskBasedCache</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ByteArrayPool"><span class="nav-number">6.</span> <span class="nav-text">ByteArrayPool</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#关于Http缓存"><span class="nav-number">7.</span> <span class="nav-text">关于Http缓存</span></a></li></ol></div>
            
          </div>
          <div class="post-toc-indicator-bottom post-toc-indicator">
            <i class="fa fa-angle-double-down"></i>
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2014 - 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">EZLippi</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="http://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
   托管在 -
  <a class="theme-link" href="https://github.com/EZLippi/EZLippi.github.io">
    Github
  </a>

</div>
<div class="theme-info">
<span id="busuanzi_container_site_pv">
    &nbsp; | &nbsp;本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
</div>
<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
</script>



      </div>
    </footer>

    <div class="back-to-top"></div>
  </div>

  


  



  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  <script type="text/javascript" src="/vendors/velocity/velocity.min.js"></script>

  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js"></script>

  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=0.5.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=0.5.0"></script>



  
  

  
  
<script type="text/javascript" src="/js/src/scrollspy.js?v=0.5.0"></script>

<script type="text/javascript" id="sidebar.toc.highlight">
  $(document).ready(function () {
    var tocSelector = '.post-toc';
    var $tocSelector = $(tocSelector);
    var activeCurrentSelector = '.active-current';

    $tocSelector
      .on('activate.bs.scrollspy', function () {
        var $currentActiveElement = $(tocSelector + ' .active').last();

        removeCurrentActiveClass();
        $currentActiveElement.addClass('active-current');

        $tocSelector[0].scrollTop = $currentActiveElement.position().top;
      })
      .on('clear.bs.scrollspy', function () {
        removeCurrentActiveClass();
      });

    function removeCurrentActiveClass () {
      $(tocSelector + ' ' + activeCurrentSelector)
        .removeClass(activeCurrentSelector.substring(1));
    }

    function processTOC () {
      getTOCMaxHeight();
      toggleTOCOverflowIndicators();
    }

    function getTOCMaxHeight () {
      var height = $('.sidebar').height() -
                   $tocSelector.position().top -
                   $('.post-toc-indicator-bottom').height();

      $tocSelector.css('height', height);

      return height;
    }

    function toggleTOCOverflowIndicators () {
      tocOverflowIndicator(
        '.post-toc-indicator-top',
        $tocSelector.scrollTop() > 0 ? 'show' : 'hide'
      );

      tocOverflowIndicator(
        '.post-toc-indicator-bottom',
        $tocSelector.scrollTop() >= $tocSelector.find('ol').height() - $tocSelector.height() ? 'hide' : 'show'
      )
    }

    $(document).on('sidebar.motion.complete', function () {
      processTOC();
    });

    $('body').scrollspy({ target: tocSelector });
    $(window).on('resize', function () {
      if ( $('.sidebar').hasClass('sidebar-active') ) {
        processTOC();
      }
    });

    onScroll($tocSelector);

    function onScroll (element) {
      element.on('mousewheel DOMMouseScroll', function (event) {
          var oe = event.originalEvent;
          var delta = oe.wheelDelta || -oe.detail;

          this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
          event.preventDefault();

          toggleTOCOverflowIndicators();
      });
    }

    function tocOverflowIndicator (indicator, action) {
      var $indicator = $(indicator);
      var opacity = action === 'show' ? 1 : 0;
      $indicator.velocity ?
        $indicator.velocity('stop').velocity({
          opacity: opacity
        }, { duration: 100 }) :
        $indicator.stop().animate({
          opacity: opacity
        }, 100);
    }

  });
</script>

<script type="text/javascript" id="sidebar.nav">
  $(document).ready(function () {
    var html = $('html');
    var TAB_ANIMATE_DURATION = 200;
    var hasVelocity = $.isFunction(html.velocity);

    $('.sidebar-nav li').on('click', function () {
      var item = $(this);
      var activeTabClassName = 'sidebar-nav-active';
      var activePanelClassName = 'sidebar-panel-active';
      if (item.hasClass(activeTabClassName)) {
        return;
      }

      var currentTarget = $('.' + activePanelClassName);
      var target = $('.' + item.data('target'));

      hasVelocity ?
        currentTarget.velocity('transition.slideUpOut', TAB_ANIMATE_DURATION, function () {
          target
            .velocity('stop')
            .velocity('transition.slideDownIn', TAB_ANIMATE_DURATION)
            .addClass(activePanelClassName);
        }) :
        currentTarget.animate({ opacity: 0 }, TAB_ANIMATE_DURATION, function () {
          currentTarget.hide();
          target
            .stop()
            .css({'opacity': 0, 'display': 'block'})
            .animate({ opacity: 1 }, TAB_ANIMATE_DURATION, function () {
              currentTarget.removeClass(activePanelClassName);
              target.addClass(activePanelClassName);
            });
        });

      item.siblings().removeClass(activeTabClassName);
      item.addClass(activeTabClassName);
    });

    $('.post-toc a').on('click', function (e) {
      e.preventDefault();
      var targetSelector = NexT.utils.escapeSelector(this.getAttribute('href'));
      var offset = $(targetSelector).offset().top;
      hasVelocity ?
        html.velocity('stop').velocity('scroll', {
          offset: offset  + 'px',
          mobileHA: false
        }) :
        $('html, body').stop().animate({
          scrollTop: offset
        }, 500);
    });

    // Expand sidebar on post detail page by default, when post has a toc.
    NexT.motion.middleWares.sidebar = function () {
      var $tocContent = $('.post-toc-content');

      if (CONFIG.sidebar.display === 'post' || CONFIG.sidebar.display === 'always') {
        if ($tocContent.length > 0 && $tocContent.html().trim().length > 0) {
          NexT.utils.displaySidebar();
        }
      }
    };
  });
</script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=0.5.0"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"ezlippi"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
  





  
  

  
  


</body>
</html>
